package eval.deploy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import eval.host.Host;
import eval.utilities.configuration.ExperimentConfiguration;
//import eval.utilities.configuration.ExperimentConfiguration;
import eval.vm.VirtualMachine;
import eval.vm.VMManager;

/**
 * This class manages the generation of the deploy track (i.e. which VM deploy
 * at each simulation cycle)
 * 
 * @author Nicolo' M. Calcavecchia <calcavecchia@elet.polimi.it>
 * 
 * */
@Singleton
public class DeployManager implements IDeployManager {

	private static ExperimentConfiguration configuration = ExperimentConfiguration.getSingleton();
	
	private static final long serialVersionUID = 1L;

	private DeploySet deployRequests[];

	@Inject
	public DeployManager() {

		deployRequests = new DeploySet[configuration.experimentTicks];
	}

	@Override
	public DeploySet getDeploySetAtTick(int tick) {
		if (tick > configuration.experimentTicks)
			throw new IllegalArgumentException(
					"Trying to retrieve the deploy set for a non-existing cycle");

		if (deployRequests[tick] == null)
			return new DeploySet();

		return deployRequests[tick];
	
	}
	
	@Override
	public List<VirtualMachine> getVMToBeRemovedAtTick(int cycle, Map<Host, List<VirtualMachine>> vmMapping) {
		List<VirtualMachine> vmToRemove = new ArrayList<VirtualMachine>();
		//List<VirtualMachine> dsAtCicle  = deployRequests[cycle].getVMs();

		for(List<VirtualMachine> dsAtCicle : vmMapping.values()){
	 
			for (VirtualMachine vm : dsAtCicle )
			{
				if(isVMRemovedAtTick(vm,cycle))
					vmToRemove.add(vm);
			}
		}
		return vmToRemove;
	}
	
	@Override
	public List<VirtualMachine> getVMToBeRemovedAtTick(int cycle, List<VirtualMachine> vmList) {
		List<VirtualMachine> vmToRemove = new ArrayList<VirtualMachine>(); 
			for(VirtualMachine vm : vmList ){
				if(isVMRemovedAtTick(vm,cycle))
					vmToRemove.add(vm);
			}
		return vmToRemove;
	}

	@Override
	public boolean isVMRemovedAtTick(VirtualMachine virtualMachine, int cycle) {
		if((cycle - virtualMachine.getStartLife()) >= virtualMachine.getLifeTime())
			return true;
		return false;
	}
	
	//TODO
	@Override
	public void setDeploySetAtTick(DeploySet ds, int tick) {
		deployRequests[tick] = ds;
	}
	
	//TODO
	@Override
	public int getVMLifetime(VirtualMachine vm, int tick) {
		return 1000;
	}
	
	public void setVmStartLife(VirtualMachine vm,int cycle)
	{
		vm.setStartLifeAtTick(cycle);
	}

}
